﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;

namespace MyVideoViewerLibrary
{
    public class MyVideoViewerBusiness
    {
        private static string[] extensions = new string[] { ".mov", ".avi", ".mpeg", ".mpg", ".mkv", ".wmv", ".mp4", ".dvr-ms", ".m2ts", ".ts" };
        public static VideoViewer VideoViewerContext { get; set; }
        static MyVideoViewerBusiness()
        {
            Settings.Default.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Default_PropertyChanged);
            ResetContext();
        }

        static void Default_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "MovieSource" || e.PropertyName == "MyMoviesServerName" || e.PropertyName == "VideoViewerServerName")
            {
                ResetContext();
            }
        }
        public static bool IsValid
        {
            get
            {
                SqlConnection conn = new SqlConnection(GetConnectionString());
                SqlCommand cmd = new SqlCommand("select count(*) from sys.databases where name = 'MyVideoViewer'", conn);

                using (conn)
                {
                    try
                    {
                        int count = 0;
                        conn.Open();
                        count = (int)cmd.ExecuteScalar();
                    }
                    catch (SqlException ex)
                    {
                        ErrorMessage = ex.Message;
                        return false;
                    }
                }
                return true;
            }
        }

        public static string ErrorMessage { get; set; }

        private static string GetConnectionString()
        {
            if (Settings.Default.MovieSource == MovieSource.MyMovies || Settings.Default.MovieSource == MovieSource.MyMoviesXML)
                return string.Format(@"Data Source={0}\MYMOVIES;Initial Catalog='MyVideoViewer';Persist Security Info=True;User ID=sa;Password=t9AranuHA7", Settings.Default.MyMoviesServerName);
            else
                return string.Format(@"Data Source={0}\SQLEXPRESS;Initial Catalog='MyVideoViewer';Persist Security Info=True;User ID=MyVideoViewerUser;Password=hAVfqNaXuj6g", Settings.Default.VideoViewerServerName);
        }

        private static void ResetContext()
        {
            if (Settings.Default.MovieSource == MovieSource.MyMovies || Settings.Default.MovieSource == MovieSource.MyMoviesXML)
                VideoViewerContext = new VideoViewer(GetConnectionString());
            else
                VideoViewerContext = new VideoViewer(GetConnectionString());
        }

        //public static void MarkTrailerAsWatched(MovieTrailer movieTrailer, bool played)
        //{
        //    VideoViewerContext.ExecuteCommand("update MovieTrailers set Watched = @p0 where MovieTrailerId = @p1", played, movieTrailer.MovieTrailerId);            
        //}
        //public static void MarkEpisodeWatchedStatus(Episode episode)
        //{
        //    //VideoViewerContext.ExecuteCommand("update Episodes set Watched = @p0 where EpisodeId = @p1", episode.Watched, episode.EpisodeId);
        //    VideoViewerContext.SubmitChanges();
        //}

        public static List<string> GetSimilarTrailers(Movie movie, int number)
        {

            VideoViewer ctx = VideoViewerContext;

            List<string> genreStrings = movie.Genres.Select(g => g.GenreDesc).ToList();
            for (int i = 0; i < genreStrings.Count; i++)
            {
                if (genreStrings[i] == "Suspense/Thriller")
                    genreStrings[i] = "Thriller";
                else if (genreStrings[i] == "Action")
                    genreStrings[i] = "Action and Adventure";
                else if (genreStrings[i] == "Adventure")
                    genreStrings[i] = "Action and Adventure";
                else if (genreStrings[i] == "Science-Fiction")
                    genreStrings[i] = "Science Fiction";
            }


            var trailers = from mg in VideoViewerContext.MovieTrailer_Genres
                           where genreStrings.Contains(mg.Genre.GenreDesc)
                           select mg.MovieTrailer;

            var watched = trailers.Where(t => t.Watched == true).ToList();
            var notwatched = trailers.Where(t => t.Watched == false).ToList();

            List<MovieTrailer> selectedTrailers = new List<MovieTrailer>();
            Random random = new Random();

            while (notwatched.Count > 0 && selectedTrailers.Count < number)
            {
                int index = random.Next(0, notwatched.Count);
                MovieTrailer trailer = notwatched[index];
                selectedTrailers.Add(trailer);
                trailer.Watched = true;
                notwatched.Remove(trailer);
            }

            while (watched.Count > 0 && selectedTrailers.Count < number)
            {
                int index = random.Next(0, watched.Count);
                MovieTrailer trailer = watched[index];
                selectedTrailers.Add(trailer);
                watched.Remove(trailer);
            }
            VideoViewerContext.SubmitChanges();
            List<string> paths = new List<string>();

            foreach (MovieTrailer mt in selectedTrailers)
            {
                DirectoryInfo di = new DirectoryInfo(mt.MovieFolder);
                if (di.Exists)
                {
                    foreach (FileInfo fi in di.GetFiles().OrderBy(f => f.LastWriteTime))
                    {
                        if (extensions.Contains(fi.Extension))
                        {
                            paths.Add(fi.FullName);
                            break;
                        }
                    }
                }
            }

            return paths;
        }

        public static int GetPlaybackTime(string filePath)
        {
            MediaPlayback mp = VideoViewerContext.MediaPlaybacks.FirstOrDefault(m => m.MediaUrl == filePath);
            if (mp == null)
                return 0;
            return mp.PlaybackTime;
        }
        public static void SetPlaybackTime(string filePath, int seconds)
        {
            MediaPlayback mp = VideoViewerContext.MediaPlaybacks.FirstOrDefault(m => m.MediaUrl == filePath);
            if (mp == null)
                mp = new MediaPlayback() { MediaUrl = filePath };
            mp.PlaybackTime = seconds;

            if (mp.MediaPlaybackId == 0)
                VideoViewerContext.MediaPlaybacks.InsertOnSubmit(mp);
            VideoViewerContext.SubmitChanges();
        }
        public static void SetPlayed(string filePath, bool played)
        {
            MediaPlayback mp = VideoViewerContext.MediaPlaybacks.FirstOrDefault(m => m.MediaUrl == filePath);
            if (mp == null)
                mp = new MediaPlayback() { MediaUrl = filePath };
            mp.Played = played;

            if (mp.MediaPlaybackId == 0)
                VideoViewerContext.MediaPlaybacks.InsertOnSubmit(mp);
            VideoViewerContext.SubmitChanges();
        }
    }
}
